package org.bb.im.client;

import org.bb.im.client.common.Const;
import org.bb.im.client.handler.HelloClientAioHandler;
import org.bb.im.packet.HelloPacket;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Node;
import org.tio.core.Tio;


public class HelloClientStarter {
    // 服务器节点
    public static Node serverNode = new Node(Const.SERVER, Const.PORT);

    // handler, 包括编码、解码、消息处理
    public static ClientAioHandler tioClientHandler = new HelloClientAioHandler();

    // 事件监听器，可以为null
    public static ClientAioListener aioListener = null;

    // 断链后自动连接，不想自动连接请设为null
    private static ReconnConf reconnConf = new ReconnConf(5000L);

    // 一组连接公用的上下文对象
    public static ClientGroupContext clientGroupContext = new ClientGroupContext(tioClientHandler, aioListener, reconnConf);

    public static TioClient tioClient = null;
    public static ClientChannelContext clientChannelContext = null;

    public static void main(String[] args) throws Exception {
        clientGroupContext.setHeartbeatTimeout(Const.TIMEOUT);
        tioClient = new TioClient(clientGroupContext);
        while (clientChannelContext == null) {
            clientChannelContext = tioClient.connect(serverNode);
        }
        send();
    }

    private static void send() throws Exception {
        HelloPacket packet = new HelloPacket();
        packet.setBody("hello world".getBytes(HelloPacket.CHARSET));
        Tio.send(clientChannelContext, packet);
    }
}
